# coding=utf-8
"""
*   Coder : Dzlua
*   Email : 505544956@qq.com
*   Time  : 2017/08/29
"""

from flask import Flask, request, url_for, render_template, jsonify
from flask_bootstrap import Bootstrap

#import MySQLdb
import math
import json, requests
#--------------------------#
app = Flask(__name__)
"""
conn = MySQLdb.connect(host='localhost',
        user='dzlua',passwd='dzlua',
        db='spider',charset="utf8")
"""
bs = Bootstrap(app)
#--------------------------#
def ajax_json_to_dict(args):
    def add_to_dict(dic, d, k, v):
        if not dic.has_key(d):
            dic[d] = {}
        dic[d][k] = v
    #
    def paser_dict(key):
        pb = key.find('[')
        pe = key.find(']')
        if pb==-1 or pe==-1:
            return False,None,None
        d = key[0 : pb]
        k = key[pb+1 : pe]
        return True,d,k
    #
    datas = {}
    for key in args:
        b,d,k = paser_dict(key)
        if b:
            add_to_dict(datas, d, k, args[key])
        else:
            datas[key] = args[key]
    return datas
#----------#
def req_for_api_test(method, action, params=None, datas=None, headers=None):
    timeout = 3
    r = None
    try:
        if method=='GET':
            r = requests.get(action, params=params, headers=headers, timeout=timeout)
        elif method=='POST':
            r = requests.post(action, params=params, headers=headers, data=datas, timeout=timeout)
    except:
        return {'req': 'error', 'res': {'text': 'error'}}
    #
    req = {
        'method': method,
        'params': params,
        'datas': datas,
        'params': params,
        'url': action,
        'headers': str(r.request.headers),
    }

    res = {
        'status_code': r.status_code,
        'url': r.url,
        'history': r.history,
        'headers': str(r.headers),
        'cookies': str(r.cookies),
        'encoding': r.encoding,
        'text': r.text,
    }

    return {'req': req, 'res': res}
#--------------------------#
@app.route('/')
def index():
    return render_template('index.html', name='Dzlua')
#----#
"""
@app.route('/libs/', methods=['GET'])
def libs():
    with conn as cur:
        #
        sql = 'SELECT count(*) FROM librarys;'
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()

        count = 0
        for r in result:
            count = r[0]
            break

        #
        idx = int(request.args.get('index')  or 0)
        limit = int(request.args.get('limit') or 20)
        if limit <= 0:
            limit = 20
        elif limit > count:
            limit = count
        #        
        idx_next = 1
        idx_prev = 0
        page = int(math.floor(count/limit))
        #
        if idx <= 0:
            idx = 0
            idx_next = idx + 1
            idx_prev = idx
        elif idx >= page:
            idx = page
            idx_next = idx
            idx_prev = idx - 1
        else:
            idx_next = idx + 1
            idx_prev = idx - 1

        sql = "SELECT id,name,type,star,lang,os,license FROM librarys WHERE id > %s ORDER BY id LIMIT %s;"
        cursor = conn.cursor()
        cursor.execute(sql, (idx * limit, limit))
        result = cursor.fetchall()
        cursor.close()

        head = '''<!DOCTYPE html> 
                <html><head> 
                <meta charset="utf-8" /> 
                <title>librarys</title> 
                </head><body>'''
        tail = '''</body></html>'''
        body = '<hr>'
        for r in result:
            body = body + ('''
                id:&nbsp;%d<br>
                name:&nbsp;<a href="%s" target="#">%s</a><br>
                type:&nbsp;%s<br>
                star:&nbsp;<font color="#FF0000">%d</font><br>
                lang:&nbsp;%s<br>
                os:&nbsp;%s<br>
                license:&nbsp;%s<br><hr>''') % \
                (r[0], url_for('lib_info', name=r[1]), r[1], r[2], r[3], r[4], r[5], r[6])
        
        nextpage = u'<div><a href="%s">首页&nbsp;</a><a href="%s">上一页&nbsp;</a>%s/%s&nbsp;<a href="%s">下一页&nbsp;</a><a href="%s">尾页</a></div>' % \
                ( url_for('libs', index=0, limit=limit),
                  url_for('libs', index=idx_prev, limit=limit),
                  idx + 1, page+1,
                  url_for('libs', index=idx_next, limit=limit),
                  url_for('libs', index=page, limit=limit) )
        return head + nextpage + body + nextpage + tail
    return 'err database'
#----#
@app.route('/libs/<name>/')
def lib_info(name):
    with conn as cur:
        sql = "SELECT id,name,type,star,lang,os,license,home,local_path,add_date,info_text,info FROM librarys WHERE name='%s';" % (name)
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()

        msg = ''
        for r in result:
            msg = '''id:&nbsp;%d<br>
                    name:&nbsp;<b>%s</b><br>
                    type:&nbsp;%s<br>
                    star:&nbsp;<font color="#FF0000">%d</font><br>
                    lang:&nbsp;%s<br>
                    os:&nbsp;%s<br>
                    license:&nbsp;%s<br>
                    home:&nbsp;<a href="%s">%s</a><br>
                    local_path:&nbsp;%s<br>
                    add_date:&nbsp;%s<br>
                    info_text:&nbsp;<br>%s
                    <hr>
                    info:&nbsp;<br>%s''' % \
                (r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[7], r[8], r[9], r[10], r[11])
            break
        return msg
    return 'err database'
"""
#----------#
@app.route('/tools/')
def tools():
    return render_template('tools.html', name='Dzlua')
#----------#
@app.route('/api/req', methods=['POST'])
def api_req():
    args = ajax_json_to_dict(request.form);
    info = req_for_api_test(**args)
    return jsonify(info)
#--------------------------#
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=25092, debug=True)
